import {fetchUserBookmark} from "@/api/modules/bookmark.ts";
import {login} from "@/api/modules/user.ts"
import {fetchUserPasswordBoxData} from "@/api/modules/password-box.ts"
import {fetchUserEngine} from "@/api/modules/engine.ts"
import {setToken} from "@/utils/token";
import {useUserStore} from "@/stores/modules/user.ts";
import {useWidgetStore} from "@/stores/modules/widget.ts";
import {clearToken} from "@/utils/token";
import {BookmarkTransformer} from "@/api/transformer/index"
import {useEngineStore} from "@/stores/modules/engine.ts";
import {decrypt} from "@/utils/crypto.ts"

/**
 * 请求登录:
 * 1. 登录
 * 2. 设置token, 用户信息等
 * 3. 获取书签, 搜索引擎以及待办
 * @param params
 */
export function requestLogin(params: any) {
    return new Promise(async (resolve, reject) => {
        const userStore = useUserStore()
        // 登录
        const loginResult = await login(params)
        if (loginResult.data.code !== 200) {
            reject("登录失败")
        }
        const {msg, data} = loginResult.data
        let {user, accessToken, tokenExpires} = data

        // 更新token和用户信息
        setToken(accessToken, tokenExpires)
        userStore.setUserInfo(user)

        // 加载用户初始化数据
        await initData()

        resolve(undefined)

    })
}

export async function initData() {
    return new Promise(async (resolve, reject) => {
        // 同步书签(请求并存入pinia)
        await initWidgets();

        // 同步搜索引擎(请求并存入pinia)
        await initEngines();
        resolve(null);
    })
}

/**
 * 登出
 * 1. 清空token和用户信息
 * 2. 删除书签, 搜索引擎, 待办
 */
export function requestLogout() {
    return new Promise(async (resolve, reject) => {
        const userStore = useUserStore();
        userStore.clearUserInfo();
        clearToken();
        resolve(null)
    })
}

function initWidgets() {
    return new Promise(async (resolve, reject) => {
        const userStore = useUserStore();
        const widgetStore = useWidgetStore();

        const res = await fetchUserBookmark({userId: userStore.id});
        if (!res || !res.data || res.data.code !== 200) {
            reject(res.data.message);
        }
        widgetStore.setWidgets(BookmarkTransformer.transform(res.data.data));
        resolve(null)
    })
}

function initEngines() {
    return new Promise(async (resolve, reject) => {
        const userStore = useUserStore();
        const engineStore = useEngineStore();

        const res = await fetchUserEngine({userId: userStore.id});
        if (!res || !res.data || res.data.code !== 200) {
            reject(res.data.message);
        }
        engineStore.setEngines(res.data.data);
        resolve(null)
    })
}

/**
 * 添加组件
 * 1. 请求接口, 添加widget
 * 2. 将数据写到vuex中(同步标签等信息)
 * 3. 返回结果
 * @param params
 */
export function requestAddWidget(params: any) {
    return new Promise(async (resolve, reject) => {
        // const res = await addWidget(params)
    })
}

export function requestSearch(params: any) {
    return new Promise(async (resolve, reject) => {
        // const res = await search(params)
    })
}

export function requestPasswordList(params: any) {
    return new Promise(async (resolve, reject) => {
        const res = await fetchUserPasswordBoxData(params)
        const data = res.data.data;
        resolve(data.map((item: any) => ({
            ...item,
            password: decrypt(item.password)
        })))
    })
}

const platformService = {
    requestLogin,
    requestLogout,
    requestAddWidget,
    requestSearch,
    initData,
    requestPasswordList
}
export default platformService